package cn.school.demo.ui.notice

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.View.*
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.setupWithNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.school.demo.MainViewModel
import cn.school.demo.MainViewModel.Companion.UPDATE_NOTICE
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentNoticeBinding
import cn.school.demo.pojo.Notice
import com.blankj.utilcode.util.LogUtils
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken


class NoticeFragment : Fragment() {

    private lateinit var mNoticeViewModel: NoticeViewModel
    private lateinit var binding: FragmentNoticeBinding

    //本地广播
    private lateinit var mLocalBroadcastManager: LocalBroadcastManager
    private lateinit var mLocalReceiver: LocalReceiver
    private val intentFilter: IntentFilter = IntentFilter()

    //RecyclerView
    private lateinit var adapter: NoticeAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(requireContext())
        mLocalReceiver = LocalReceiver()
        intentFilter.apply {
            addAction(UPDATE_NOTICE)
        }
        mLocalBroadcastManager.registerReceiver(mLocalReceiver, intentFilter)

//        val workRequest = OneTimeWorkRequest.Builder(NoticeWorker::class.java).build()
//        WorkManager.getInstance().enqueue(workRequest)
        MainViewModel().getNoticeList()
        mNoticeViewModel =
            ViewModelProvider(this).get(NoticeViewModel::class.java)

        binding = FragmentNoticeBinding.inflate(inflater, container, false)
        binding.noticeRecyclerView.layoutManager = LinearLayoutManager(requireContext())
        val root: View = binding.root
        val navView: BottomNavigationView = binding.navView
        val navController = findNavController()
        navView.setupWithNavController(navController)
        binding.noticeProgressBar.visibility = VISIBLE
        requireActivity().window.apply {
            statusBarColor = Color.argb(1,249,249,249)
            decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }
        update()
        return root
    }

    private fun updateUI() {
        binding.noticeProgressBar.visibility = View.INVISIBLE
        val notices = mNoticeViewModel.notice
        adapter = NoticeAdapter(notices)
        binding.noticeRecyclerView.adapter = adapter
        mNoticeViewModel.oldY = mNoticeViewModel.newY
    }

    private inner class LocalReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent!!.action) {
                UPDATE_NOTICE -> {
                    LogUtils.e("我收到了更新Notice的广播")
                    val notices = Gson().fromJson<List<Notice>>(
                        intent.getStringExtra("notice"),
                        object : TypeToken<List<Notice>>() {}.type
                    )
                    mNoticeViewModel.updateNotice(notices as MutableList<Notice>)
                    updateUI()
                }
            }
        }
    }

    fun update() {
        /* *
        * 下拉刷新
        * */
        binding.noticeRecyclerView.addOnScrollListener(object :
            RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                val isTop = recyclerView.canScrollVertically(-1)
                mNoticeViewModel.isTop = !isTop
                val isBottom = recyclerView.canScrollVertically(1)
                mNoticeViewModel.isBottom = !isBottom
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                mNoticeViewModel.apply {
                    isTop = dy > 0
                    isBottom = false
                }
            }
        })
        binding.noticeRecyclerView.addOnItemTouchListener(object :
            RecyclerView.OnItemTouchListener {
            override fun onInterceptTouchEvent(
                rv: RecyclerView,
                motionEvent: MotionEvent
            ): Boolean {
                when (motionEvent.actionMasked) {
                    MotionEvent.ACTION_DOWN -> {
                        //LogUtils.d("down:" + motionEvent.y)
                        mNoticeViewModel.oldY = motionEvent.y
                    }
                    MotionEvent.ACTION_MOVE -> {
                        //LogUtils.e("move:" + motionEvent.y)
                        //viewModel.newY = motionEvent.y
                    }
                    MotionEvent.ACTION_UP -> {
                        //LogUtils.e(motionEvent.y)
                        mNoticeViewModel.newY = motionEvent.y
                        if (mNoticeViewModel.newY - mNoticeViewModel.oldY > 3 && mNoticeViewModel.isTop) {
                            binding.noticeProgressBar.visibility = View.VISIBLE
                            MainViewModel().getNoticeList()
                        }

                    }
                }
                return false
            }

            override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
                //TODO("Not yet implemented")
            }

            override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
                //TODO("Not yet implemented")
            }

        })
    }

    private inner class NoticeHolder(view: View) : RecyclerView.ViewHolder(view),
        View.OnClickListener {
        private lateinit var notice: Notice
        private val titleTextView = itemView.findViewById<TextView>(R.id.notice_title)
        private val dateTextView = itemView.findViewById<TextView>(R.id.notice_date)

        init {
            itemView.setOnClickListener(this)
        }

        fun bind(notice: Notice) {
            this.notice = notice
            titleTextView.text = this.notice.title
            dateTextView.text = this.notice.date
        }

        override fun onClick(v: View) {
            LogUtils.e(notice.url)
            val amount = "https://www.sdtbu.edu.cn" + notice.url.substring(2)
            val bundle = bundleOf(Pair("url", amount))
            findNavController().navigate(R.id.action_Notice_to_WebView, bundle)

        }
    }

    private inner class NoticeAdapter(var notices: MutableList<Notice>) :
        RecyclerView.Adapter<NoticeHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoticeHolder {
            val view = layoutInflater.inflate(R.layout.list_item_notice, parent, false)
            return NoticeHolder(view)
        }

        override fun onBindViewHolder(holder: NoticeHolder, position: Int) {
            val notice = notices[position]
            holder.bind(notice)
        }

        override fun getItemCount() = notices.size

    }

}